<template>
  <div class="view">
    <el-row class="handle-box" :model="filters">
      <el-col :span="8">
        <el-button
          class="jianbianbule"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          >{{ $t("userinfo.userinfo") }}</el-button
        >
      </el-col>
      <el-col :span="16" style="text-align: right;">
        <span>{{ $t("userinfo.username") }}：</span>
        <el-input
          v-model="filters.userName"
          @keyup.native.enter="search"
          :placeholder="$t('public.text')"
          clearable
        ></el-input>
        <span>{{ $t("userinfo.role") }}：</span>
        <el-select
          v-model="filters.roleId"
          filterable
          clearable
          @change="search"
          :placeholder="$t('public.select')"
        >
          <el-option
            v-for="item in roleIds"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          >
          </el-option>
        </el-select>
        <span>{{ $t("userinfo.usergroup") }}：</span>
        <el-select
          v-model="filters.ugid"
          filterable
          clearable
          @change="search"
          :placeholder="$t('public.select')"
        >
          <el-option
            v-for="item in userGroups"
            :key="item.ugId"
            :label="item.userGroupName"
            :value="item.ugId"
          >
          </el-option>
        </el-select>
        <el-button class="seacthsbtn" type="primary" id="btn" @click="search" icon="el-icon-search">{{$t("public.search")}}</el-button>
      </el-col>
    </el-row>
    <div class="tablebox">
    <template>
      <el-table :data="tables" size="mini" stripe class="tablefisbox">
        <el-table-column type="index" :label="$t('public.number')" width="60">
        </el-table-column>
        <el-table-column prop="userName" min-width="70" :label="$t('userinfo.userName')">
        </el-table-column>
        <el-table-column prop="gender" min-width="40" :label="$t('userinfo.gender')">
          <template slot-scope="scope">
            {{ scope.row.gender ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column prop="account" :label="$t('userinfo.account')"> </el-table-column>
        <el-table-column
          prop="userGroupName"
          show-overflow-tooltip
          :label="$t('userinfo.userGroupName')"
        >
        </el-table-column>
        <el-table-column prop="roleName" :label="$t('userinfo.role')"> </el-table-column>
        <el-table-column
          prop="wellTypeName"
          show-overflow-tooltip
          :label="$t('userinfo.wellTypeName')"
        >
        </el-table-column>
        <el-table-column
          prop="companyName"
          show-overflow-tooltip
          :label="$t('userinfo.companyName')"
        >
        </el-table-column>
        <el-table-column prop="phoneNumber" min-width="100" :label="$t('userinfo.phoneNumber')">
        </el-table-column>
        <el-table-column
          prop="email"
          min-width="110"
          show-overflow-tooltip
          :label="$t('userinfo.email')"
        >
        </el-table-column>
        <el-table-column prop="accountState" :label="$t('userinfo.accountState')">
          <template slot-scope="scope">
            {{ scope.row.accountState ? "启用" : "禁用" }}
          </template>
        </el-table-column>
        <el-table-column prop="userState" :label="$t('userinfo.userState')">
          <template slot-scope="scope">
            {{ scope.row.userState ? "在线" : "下线" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :formatter="carTimeFilter"
          min-width="140"
          :label="$t('public.createTime')"
        >
        </el-table-column>
        <el-table-column :label="$t('public.operation')" width="300">
          <template slot-scope="scope">
            <el-button
              type="warning"
              icon="el-icon-edit"
              round
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >{{ $t("public.edit") }}</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="red"
              round
              size="mini"
              @click="handleDel(scope.$index, scope.row)"
              >{{ $t("public.del") }}</el-button
            >
            <el-button
              type="success"
              icon="el-icon-refresh-right"
              class="red"
              title="reset password"
              round
              size="mini"
              @click="handleReset(scope.$index, scope.row)"
              >{{ $t("public.reset") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
       
    </template>

    <!--工具条-->
    <el-col class="pages">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pageSize"
        :total="total"
      >
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog
      class="dialogs"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="700px"
    >
      <el-form ref="editForm" :model="editForm" :rules="editFormRules">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.userName')" prop="userName">
              <el-input v-model="editForm.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.gender')" prop="sex">
              <el-radio-group v-model="editForm.sex">
                <el-radio :label="true">{{ $t("public.body") }}</el-radio>
                <el-radio :label="false">{{ $t("public.girl") }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.account')" prop="account">
              <el-input
                v-model="editForm.account"
                :disabled="dbAccount"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.passWords')" prop="passWords">
              <el-input v-model="editForm.passWords"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.phoneNumber')" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="email"
              :label="$t('userinfo.email')"
              :rules="[
                {
                  type: 'email',
                  message: '请输入正确的邮箱地址',
                  trigger: ['blur', 'change'],
                },
              ]"
            >
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.role')" prop="roleId">
              <el-select
                v-model="editForm.roleId"
                clearable
                filterable
                :placeholder="$t('public.select')"
              >
                <el-option
                  v-for="item in roleIds"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('userinfo.accountState')" prop="accountState">
              <el-radio-group v-model="editForm.accountState">
                <el-radio :label="1">{{$t("userinfo.open")}}</el-radio>
                <el-radio :label="0">{{$t("userinfo.forbid")}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
            :label="$t('userinfo.wellTypeName')"
            label-width=""
            prop="wellType"
            class="wellType"
          >
            <el-select
              v-model="editForm.wellType"
              style="width: 540px"
              multiple
              clearable
              filterable
              :placeholder="$t('public.select')"
            >
              <el-option
                v-for="item in wellTypes"
                :key="item.wid"
                :label="item.wellType"
                :value="item.wid"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="$t('userinfo.userGroupName')" class="userGroupId" prop="userGroupId">
            <el-select
              v-model="editForm.userGroupId"
              style="width: 540px"
              clearable
              filterable
              :placeholder="$t('public.select')"
            >
              <el-option
                v-for="item in userGroups"
                :key="item.ugId"
                :label="item.userGroupName"
                :value="item.ugId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="$t('userinfo.companyName')" prop="company" class="company">
            <el-select
              v-model="editForm.company"
              style="width: 540px"
              clearable
              multiple
              filterable
              :placeholder="$t('public.select')"
            >
              <el-option
                v-for="item in companys"
                :key="item.comId"
                :label="item.comName"
                :value="item.comId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogFormVisible = false" type="success">{{
          $t("public.cancelbtn")
        }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
          >{{ $t("public.savebtn") }}</el-button
        >
        <el-button v-else type="primary" @click="updateData">{{
          $t("public.changebtn")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogStatus: "", //编辑框界面切换
      textMap: {
        //添加与编辑界面
        update: this.$t("public.edit"),
        create: this.$t("public.create"),
      },
      dialogFormVisible: false, //弹窗
      //查询条件字段
      filters: {
        userName: "",
        roleId: "",
        ugid: "",
      },
      tables: [], //表格数据
      total: 0, //总共条数
      page: 1, //请求页
      limit: 10, //页条数
      pageSize: 1, //当前页
      dbAccount: false,
      //是否必填项
      editFormRules: {
        userName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        passWords: [{ validator: this.validateMobile, trigger: "blur" }],
        userGroup: [
          { required: true, message: "请选择用户组", trigger: "blur" },
        ],
      },
      //编辑界面数据
      editForm: {
        userName: "",
        wellType: [],
        account: "",
        passWords: "",
        userGroupId: "",
        sex: "",
        phoneNumber: "",
        roleId: "",
        accountState: "",
        email: "",
        company: [],
      },
      wellTypes: [], //井类型
      userGroups: [], //用户组
      roleIds: [], //角色管理
      companys: [], //作业公司
    };
  },
  watch: {
    "filters.userName"(val) {
      if (val.trim() === "") {
        this.getUserinfo();
      }
    },
  },
  mounted() {
    this.getUserinfo();
    this.getSelect();
  },
  methods: {
    handleSizeChange(val) {
      this.limit = val;
      this.getUserinfo();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.pageSize = val;
      this.getUserinfo();
    },
    //显示编辑界面
    handleEdit(index, row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.dbAccount = true;
      this.editForm = {
        userId: row.userId,
        userName: row.userName,
        sex: row.gender,
        phoneNumber: row.phoneNumber,
        account: row.account,
        email: row.email,
        userGroupId: row.userGroupId,
        passWords: "",
        accountState: row.accountState,
        wellType: row.wellTypeId,
        company: row.companyId,
        roleId: row.roleId,
        createUser: JSON.parse(this.$store.state.userInfo).uid,
        createTime: row.createTime,
      };
    },
    //显示新增界面
    handleAdd() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.dbAccount = false;
      this.editForm = {
        userName: "",
        wellType: [],
        account: "",
        passWords: "",
        userGroup: "",
        sex: true,
        phoneNumber: "",
        roleId: "",
        accountState: 1,
        email: "",
        company: [],
        createUser: JSON.parse(this.$store.state.userInfo).uid,
      };
    },
    //模糊搜索
    search() {
      this.page = 1;
      this.limit = 10;
      this.pageSize = 1;
      this.getUserinfo();
    },
    //获取用户
    async getUserinfo() {
      try {
        let params = {
          UseName: this.filters.userName,
          RoleId: this.filters.roleId,
          Ugid: this.filters.ugid,
          page: this.page,
          limit: this.limit,
        };
        let res = await this.$api.management.getUserinfo(params);
        this.total = res.count;
        this.tables = res.data;
      } catch (e) {
        console.log(e);
      }
    },

    //获取下拉数据
    async getSelect() {
      //井类型数据
      let wellTypes = await this.$api.set.welltypeSelect();
      this.wellTypes = wellTypes.data;
      //用户组数据
      let userGroups = await this.$api.management.getseleUsergroup();
      this.userGroups = userGroups.data;
      //角色选择数据
      let roleIds = await this.$api.management.getseleRole();
      this.roleIds = roleIds.data;
      //作业公司数据
      let companys = await this.$api.set.companySelect();
      this.companys = companys.data;
    },
    //添加用户
    createData() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let params = Object.assign({}, this.editForm);
          let res = await this.$api.management.addUser(params);
          if (res.code == 200) {
            this.$message({
              message: this.$t("public.addsuccess"),
              type: "success",
            });
            this.$refs["editForm"].resetFields(); //清空表单
            this.dialogFormVisible = false; //关闭弹窗
            this.getUserinfo(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        }
      });
    },
    //修改用户 调用方法
    updateData() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let params = Object.assign({}, this.editForm);
          let res = await this.$api.management.editUsers(params);
          if (res.code == 200) {
            this.$message({
              message: this.$t("public.editsuccess"),
              type: "success",
            });
            this.$refs["editForm"].resetFields(); //清空表单
            this.dialogFormVisible = false;
            this.getUserinfo(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        }
      });
    },
    //删除用户 调用方法
    handleDel(index, row) {
      // 二次确认删除
      this.$confirm(
        this.$t("public.confirmcontent"),
        this.$t("public.confirmtitle"),
        {
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            id: row.userId,
            usid: JSON.parse(this.$store.state.userInfo).uid,
          };
          let res = await this.$api.management.removeUserinfo(params);
          if (res.code == 200) {
            this.$message.success(this.$t("public.confirmtips1"));
            this.getUserinfo(); //刷新数据
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch(() => {});
    },
    //重置密码
    handleReset(index, row) {
      // 二次确认重置
      this.$confirm(
        this.$t("public.confirmreset"),
        this.$t("public.confirmtitle"),
        {
          type: "warning",
        }
      )
        .then(async () => {
          let params = {
            usid: JSON.parse(this.$store.state.userInfo).uid,
            adminid: row.userId,
          };
          await this.$api.management.rpwd(params);

          this.$message.success(this.$t("public.resetsuccess"));
          this.getUserinfo(); //刷新数据
        })
        .catch(() => {});
    },
    //时间格式化
    carTimeFilter(row, column, cellValue, index) {
      const daterc = row[column.property];
      if (daterc != null) {
        return this.$moment(daterc).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    //密码格式验证
    validateMobile(rule, value, callback) {
      var reg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、])[A-Za-z\d`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{8,18}$/;
      if (value !== "") {
        if (value.length < 8) {
          callback(new Error("请输入至少8位的密码"));
        } else if (!reg.test(value)) {
          callback(new Error("密码必须包含字母、数字和特殊字符"));
        } else {
          callback();
        }
      } else if (this.dialogStatus == "create") {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    },
  },
};
</script>

<style>
.el-radio {
  color: #ffffff;
}
</style>